<template>
    <view
        class="pages"
        :class="themeName"
        :style="
            'background-image: url(' +
            $getImageUri('resource/image/shopapi/default/login_bg.png') +
            ')'
        "
    >
        <view class="login">
            <u-navbar
                v-if="!isWeixin"
                :is-back="true"
                :background="{ background: `rgba(256,256,256,0)` }"
            >
            </u-navbar>
            <image class="logo" :src="appConfig.logo" mode="heightFix"></image>
            <view class="acount-login">
                <view v-if="userLoginWay == 2">
                    <view class="input">
                        <u-field
                            label-width="0"
                            v-model="account"
                            placeholder="请输入手机号"
                            :border-bottom="false"
                            :input-border="false"
                            :style="{ width: '100%' }"
                        />
                    </view>
                    <view class="input">
                        <u-field
                            v-if="loginType == 1"
                            label-width="0"
                            v-model="password"
                            type="password"
                            :border-bottom="false"
                            :password-icon="false"
                            placeholder="请输入密码"
                            :input-border="false"
                        >
                            <view class="forget-btn p-l-20" slot="right">
                                <router-link to="/pages/forget_pwd/forget_pwd">
                                    忘记密码?
                                </router-link>
                            </view>
                        </u-field>
                        <u-field
                            v-if="loginType == 2"
                            label-width="0"
                            v-model="code"
                            placeholder="请输入验证码"
                            :border-bottom="false"
                            :input-border="false"
                        >
                            <view slot="right">
                                <view class="sms-btn" @tap="sendSMS">
                                    <!-- 获取验证码 -->
                                    <u-verification-code
                                        unique-key="login"
                                        ref="uCode"
                                        @change="codeChange"
                                    >
                                    </u-verification-code>
                                    <view class="p-l-20 garyTipsText">{{ codeTips }} </view>
                                </view>
                            </view>
                        </u-field>
                    </view>
                </view>
                <defaultLogin
                    v-if="userLoginWay == 1"
                    @mnLogin="mnpLogin"
                    @getCodeUrl="getCodeUrl"
                    @appLogin="appLogin"
                    @ttLogin="ttLogin"
                    @changeLoginWay="userLoginWay = 2"
                    :isWeixin="isWeixin"
                >
                </defaultLogin>
                <view class="agreementSelect m-b-40">
                    <u-checkbox :active-color="themeColor" v-model="agreementValue">
                        <view class="sm flex row-center">
                            已阅读并同意
                            <router-link
                                data-theme=""
                                to="/bundle/pages/server_explan/server_explan?type=1"
                            >
                                <view class="agreement">《服务协议》</view>
                            </router-link>
                            和
                            <router-link to="/bundle/pages/server_explan/server_explan?type=2">
                                <view class="agreement">《隐私协议》</view>
                            </router-link>
                        </view>
                    </u-checkbox>
                </view>
                <view v-if="userLoginWay == 2">
                    <button class="login-btn white" size="lg" @tap="loginFun">登录</button>
                    <view class="flex row-between">
                        <view>
                            <view
                                class="lighter"
                                v-if="hasLoginWay(1) && loginType == 2"
                                @tap="changeLoginType"
                            >
                                <text>已有账号，使用</text>
                                <text>密码登录</text>
                            </view>
                            <view
                                class="lighter"
                                v-if="hasLoginWay(2) && loginType == 1"
                                @tap="changeLoginType"
                            >
                                <text>已有账号，使用</text>
                                <text>验证码登录</text>
                            </view>
                        </view>
                        <router-link
                            class="lighter"
                            to="/pages/register/register"
                            v-if="isPhoneRegister"
                        >
                            注册账号
                        </router-link>
                    </view>
                </view>
            </view>
        </view>
        <!-- #ifdef MP-WEIXIN -->
        <mplogin-popup
            v-model="showLoginPop"
            :logo="appConfig.logo"
            :title="appConfig.shop_name"
            :login-data="loginData"
            @close="closePopup"
            @update="handleSubmitInfo"
        />
        <!--  #endif -->
    </view>
</template>

<script>
import defaultLogin from './components/defaultLogin.vue'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import {
    apiAuthLogin,
    apiAccountLogin,
    apiLoginCaptcha,
    apiToutiaoAuthLogin,
    apiAppWxLogin,
    apiUpdateUser
} from '@/api/app'
import wechath5 from '@/utils/wechath5'
import { isWeixinClient, currentPage, client, trottle, getClient } from '@/utils/tools'
import { ClientEnum } from '@/utils/enum'
import Cache from '@/utils/cache'
import { BACK_URL, INVITE_CODE } from '@/config/cachekey'
import { getCode, getUserProfile } from '@/utils/login'

const loginType = {
    ACCOUNT: 1,
    SMS_CODE: 2
}
export default {
    data() {
        return {
            password: '',
            account: '',
            code: '',
            loginType: '',
            isWeixin: '',
            codeTips: '',
            showLoginPop: false,
            loginData: {},
            agreementValue: false, //协议同意
            userLoginWay: 1 //1-一键登录 2-账号登录
        }
    },
    components: {
        defaultLogin
    },
    methods: {
        ...mapMutations(['login']),
        ...mapActions(['getUser']),

        // 小程序微信登录
        async mnpLogin() {
            if (!this.agreementValue) {
                this.$toast({ title: '请阅读并同意《服务协议》和《隐私协议》！' })
                return
            }
            const {
                userInfo: { avatarUrl, nickName, gender }
            } = await getUserProfile()
            uni.showLoading({
                title: '登录中...',
                mask: true
            })
            const wxCode = await getCode()
            const data = await apiAuthLogin({
                code: wxCode,
                nickname: nickName,
                headimgurl: avatarUrl
            })
            if (data.is_new_user) {
                uni.hideLoading()
                this.showLoginPop = true
                this.loginData = data
            } else {
                this.loginHandle(data)
            }
            // this.loginHandle(data)
        },
        getCodeUrl() {
            if (!this.agreementValue) {
                this.$toast({ title: '请阅读并同意《服务协议》和《隐私协议》！' })
                return
            }
            wechath5.getWxUrl()
        },
        // 公众号微信登录
        async oaLogin(code) {
            if (!code) return
            const data = await wechath5.authLogin(code)
            this.loginHandle(data)
        },
        oaAutoLogin() {
            // H5微信登录
            const { code } = this.$Route.query

            this.isWeixin = isWeixinClient()
            if (this.isLogin) {
                // 已经登录 => 首页
                uni.switchTab({
                    url: '/pages/index/index'
                })
                return
            }
            if (code) {
                // 带有code => 登录
                return this.oaLogin(code)
            }
            if (this.isWeixin && this.isOaWxAutoLogin) {
                // 开启自动授权登录
                wechath5.getWxUrl()

                // this.getCodeUrl()
            }
        },
        // app微信登录
        async appLogin() {
            if (!this.agreementValue) {
                this.$toast({ title: '请阅读并同意《服务协议》和《隐私协议》！' })
                return
            }
            uni.login({
                provider: 'weixin',
                success: (res) => {
                    uni.showLoading({
                        title: '登录中...',
                        mask: true
                    })
                    const { openid, access_token } = res.authResult
                    apiAppWxLogin({
                        openid,
                        access_token
                    })
                        .then((res) => {
                            this.loginHandle(res)
                        })
                        .finally((res) => {
                            uni.hideLoading()
                        })
                }
            })
        },
        // 账号登录
        async loginFun() {
            const { account, password, telephone, code, loginType, agreementValue } = this
            console.log(!agreementValue)
            if (!agreementValue) {
                this.$toast({ title: '请阅读并同意《服务协议》和《隐私协议》！' })
                return
            }
            if (!account) {
                this.$toast({
                    title: '请输入手机号'
                })
                return
            }

            if (this.loginType == 1 && !password) {
                this.$toast({
                    title: '请输入密码'
                })
                return
            }
            if (this.loginType == 2 && !code) {
                this.$toast({
                    title: '请输入验证码'
                })
                return
            }

            apiAccountLogin({
                scene: loginType,
                account,
                password: loginType == 1 ? password : '',
                code: loginType == 2 ? code : ''
            }).then((res) => {
                this.loginHandle(res)
            })
        },
        // 登录结果处理
        async loginHandle(data) {
            this.login(data)
            this.getUser()
            // 更新购物车
            this.$store.dispatch('getCartNum')
            uni.hideLoading()
            if (this.isBindMobile && !data.mobile) {
                return this.$Router.replace('/pages/bind_mobile/bind_mobile')
            }
            this.goBack()
        },
        goBack() {
            if (getCurrentPages().length > 1) {
                this.$Router.back(1, {
                    success: () => {
                        const { onLoad, options } = currentPage()
                        // 刷新上一个页面
                        onLoad && onLoad(options)
                    }
                })
            } else if (Cache.get(BACK_URL)) {
                this.$Router.replace(Cache.get(BACK_URL))
            } else {
                this.$Router.replaceAll('/pages/index/index')
            }
            Cache.remove(BACK_URL)
        },
        changeLoginType() {
            if (this.loginType == loginType.ACCOUNT) {
                this.loginType = loginType.SMS_CODE
            } else if (this.loginType == loginType.SMS_CODE) {
                this.loginType = loginType.ACCOUNT
            }
        },
        // 发送验证码
        sendSMS() {
            if (!this.$refs.uCode.canGetCode) return
            if (!this.account) {
                this.$toast({
                    title: '请输入手机号'
                })
                return
            }
            apiLoginCaptcha({
                mobile: this.account
            }).then((res) => {
                this.$refs.uCode.start()
            })
        },

        codeChange(tip) {
            this.codeTips = tip
        },
        // 头条小程序登录
        async ttLogin() {
            const code = await getCode()
            const [err, res] = await uni.getUserInfo()
            if (!res) {
                this.openSetting()
                return
            }
            const { avatarUrl, nickName } = res.userInfo
            uni.showLoading({
                title: '登录中...'
            })

            apiToutiaoAuthLogin({
                code,
                avatarUrl,
                nickName
            })
                .then((res) => {
                    this.loginHandle(res)
                })
                .catch((res) => {
                    console.log(res)
                    uni.hideLoading()
                })
        },
        openSetting() {
            uni.showModal({
                title: '温馨提示',
                content: '您已拒绝授权，是否前往设置打开个人信息授权？',
                confirmColor: this.themeColor,
                success(res) {
                    if (res.confirm) {
                        uni.openSetting()
                    }
                }
            })
        },
        async handleSubmitInfo(e) {
            const loginData = this.loginData
            const res = await apiUpdateUser(e, loginData.token)
            this.loginHandle(loginData)
        },
        closePopup() {
            this.showLoginPop = false
        }
    },
    computed: {
        // 开启手机号注册
        isPhoneRegister() {
            const { register_way } = this.appConfig
            if (!register_way) {
                return false
            }
            return register_way.some((item) => item == 1)
        },
        // 开启强制绑定手机号
        isBindMobile() {
            const { coerce_mobile } = this.appConfig
            return coerce_mobile
        },
        // 登录方式数组
        loginWay() {
            const { login_way } = this.appConfig
            if (!login_way) return false
            this.loginType = login_way[0] || ''
            return login_way
        },
        // 是否包含对应的登录方式
        hasLoginWay() {
            return (type) => {
                return this.loginWay && this.loginWay.some((item) => item == type)
            }
        },
        // 开启小程序微信授权
        isMnpWxAuth() {
            const { mnp_wechat_auth } = this.appConfig
            return mnp_wechat_auth
        },

        // 开启小程序微信授权
        isOaWxAuth() {
            const { h5_wechat_auth } = this.appConfig
            return h5_wechat_auth
        },
        // 开启app微信授权
        isAPPWxAuth() {
            const { app_wechat_auth } = this.appConfig
            return app_wechat_auth
        },
        // 开启公众号微信自动登录
        isOaWxAutoLogin() {
            const { h5_auto_wechat_auth } = this.appConfig
            return h5_auto_wechat_auth
        },
        // 开启小程序头条登录
        isToutiaoAuth() {
            const { toutiao_auth } = this.appConfig
            return toutiao_auth
        }
    },
    onLoad() {
        this.mnpLogin = trottle(this.mnpLogin)
        this.appLogin = trottle(this.appLogin)
        this.getCodeUrl = trottle(this.getCodeUrl)
        this.ttLogin = trottle(this.ttLogin)
        getClient() == ClientEnum['H5'] ? (this.userLoginWay = 2) : (this.userLoginWay = 1)
        // #ifdef H5
        this.oaAutoLogin()
        // #endif
    },
    onUnload() {}
}
</script>
<style lang="scss">
page {
    // background-color: #fff;

    height: 100vh;
    padding: 0;
}

.login {
    height: 100vh;
    padding-top: 80rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .logo {
        height: 260rpx;
        // width: 260rpx;
        border-radius: 20rpx;
        margin-bottom: 140rpx;
    }

    .acount-login,
    .other-login {
        width: calc(100% - 80rpx);

        .input {
            height: 100rpx;
            display: flex;
            align-items: center;
            border: 1px solid #d7d7d7;
            border-radius: 12rpx;

            &:nth-child(1) {
                // margin-top: 140rpx;
            }

            &:nth-child(2) {
                margin-top: 40rpx;
            }
        }

        .login-btn {
            height: 100rpx;
            line-height: 100rpx;
            margin: 30rpx 0 50rpx;
            @include background_color();
        }

        .forget-btn {
            border-left: $-solid-border;
        }

        .sms-btn {
            border-left: $-solid-border;

            // text-align: center;
            // border: 1px solid;
            // width: 176rpx;
            // height: 60rpx;
            // line-height: 60rpx;
            // border-radius: 60rpx;
            // @include font_color();
            // @include border_color();
            .redTipsText {
                @include font_color();
            }

            .garyTipsText {
                color: #888888;
            }
        }

        .wx-login {
            margin-top: 60rpx;

            .image {
                margin-top: 40rpx;
                width: 80rpx;
                height: 80rpx;
            }
        }
    }

    .agreementSelect {
        margin-top: 40rpx;
        display: flex;
        // align-items: center;
        justify-content: start;
    }

    .agreement {
        @include font_color;
    }

    .lighter {
        text {
            &:nth-child(2) {
                @include font_color();
            }
        }
    }
}
</style>
